package ext.tianma.workflow;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Locale;
import java.util.PropertyResourceBundle;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import wt.doc.WTDocument;
import wt.epm.EPMDocument;
import wt.fc.Persistable;
import wt.fc.WTObject;
import wt.inf.container.WTContained;
import wt.inf.container.WTContainer;
import wt.inf.library.WTLibrary;
import wt.part.WTPart;
import wt.pdmlink.PDMLinkProduct;
import wt.session.SessionHelper;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTProperties;
import ext.com.iba.IBAUtil;

public class PdfReadExcelGuidUtil {
	public static boolean VERBOSE = false;
	public static WTProperties wtProperties;
	private static String CLASSNAME = PdfReadExcelGuidUtil.class.getName();
	private static String ES_CFG = "eSignatureCfg";
	private static String PROEPETIESFILE = "ext.shantuict.wfaugment.wfaugment";
	public static Hashtable container2label = new Hashtable(); // 容器类与电子签名指南标记对应表
	public static Hashtable class2label = new Hashtable(); // 业务对象类与电子签名标记对应表
	static
	{
		try
		{
			wtProperties = WTProperties.getLocalProperties();
			VERBOSE = wtProperties.getProperty("ext.shantuict.esignature.verbose", true);
			container2label.put(WTLibrary.class.getName(), "WTLibrary");
			container2label.put(PDMLinkProduct.class.getName(), "PDMLinkProduct");
			class2label.put(WTDocument.class.getName(), "doc");
			class2label.put(EPMDocument.class.getName(), "cad");
			class2label.put(WTPart.class.getName(), "cad");
		}
		catch (java.io.IOException ioe)
		{
			ioe.printStackTrace();
		}
	}
	/**
	 *输出调试信息
	 */
	private static void outDebugInfo(String info)
	{
		if(VERBOSE)
			System.out.println("..."+CLASSNAME+"..."+info);
	}	
	/**
	 *读取Excel中的配置信息
	 * 
	 * @param pbo  
	 * @param sheetname
	 * @param bigtype
	 * @param smalltype
	 * @return Hashtable Key 为标题  value为配置值
	 * @throws WTException
	 */
	public static Hashtable getConfigInfoForDoc(WTObject pbo,String sheetname,String bigtype,String smalltype) throws IOException, WTException
	{
		Hashtable configinfor = new Hashtable();
		outDebugInfo(">>> .getConfigInfoForObject");
		String wfConfigFilePath = getConfigFilePath(pbo);
		if (VERBOSE)
			System.out.println(CLASSNAME + "	配置路径=" + wfConfigFilePath);
		if (wfConfigFilePath == null || wfConfigFilePath.length() == 0)
			return null;
		FileInputStream readFile = null;
		try
		{
			readFile = new FileInputStream(wfConfigFilePath);
			XSSFWorkbook wb = new XSSFWorkbook(readFile);
			if (wb == null)
			{
				outDebugInfo("	无法读取配置表，请检查配置表是否存在以及文件是否正常");
				return null;
			}
			XSSFSheet sheet = wb.getSheet(sheetname);
			if (sheet == null)
			{
				outDebugInfo("	无法读取配置表中的表" + sheetname);
				return null;
			}
			int rowNumber = 0;
			// -----开始根据对象大类/小类解析配置文件
			XSSFRow row;
			int nSheetRow = sheet.getLastRowNum();
			row = sheet.getRow(0);
			int nSheetCol = row.getLastCellNum();
			// 小类的位置
			for (int i = 1; i < nSheetRow; i++)
			{
				// 对象大类
				String s = getExcelCellContent(sheet, i, 0);
				if (bigtype.length() != 0 && s.equalsIgnoreCase(bigtype))
				{
					// 针对无小类的对象大类：取对象大类所在行
					if (smalltype == null || smalltype.length() == 0)
					{
						rowNumber = i + 1;
						break;
					}
					else
					{
						// 对象小类
						for (int j = i + 1; j < nSheetRow; j++)
						{
							String ss = getExcelCellContent(sheet, j, 1);
							// 到达下一个大类时跳出循环
							if (ss == null || ss.length() == 0)
								break;
							else if (smalltype.length() != 0 && ss.equalsIgnoreCase(smalltype))
							{
								rowNumber = j;
								break;
							}
						}
					}
				}
				if (rowNumber != 0)
					break;
			}
			if (rowNumber == 0)
			{
				outDebugInfo(  "  配置文件中没有对应的大类或小类");
				return null;
			}
			outDebugInfo("\t rowNumber = " + rowNumber);
			// -----结束检索配置表;
			// 小类的位置
			for (int i = 2; i < nSheetCol; i++)
			{
				String key = getExcelCellContent(sheet, 0, i);
				String value=getExcelCellContent(sheet, rowNumber, i);
				if(key!=null&&key.length()>0)
				{
					configinfor.put(key, value);
				}
			}
		}
		finally
		{
			if (readFile != null)
				readFile.close();
		}
		outDebugInfo("getConfigInfoForObject=" + configinfor);
		return configinfor;
	}
    //读取楚天中文档的签名配置信息
	public static Hashtable getConfigInforDoc(WTDocument doc) throws IOException, WTException
	{
		String ibaconfig = getPropertiesValue(PROEPETIESFILE, "wf.doc.smallType");
		Hashtable ibaValues = IBAUtil.getIBAValues(doc);
		String smallType = (String) ibaValues.get(ibaconfig);
		Locale locale = SessionHelper.manager.getLocale();
		String docType = ClientTypedUtility.getLocalizedTypeName(doc, locale);
		Hashtable configinfor = PdfReadExcelGuidUtil.getConfigInfoForDoc(doc, "doc", docType, smallType);
		outDebugInfo("getConfigInforDoc=" + configinfor);
		return configinfor;

	}
	/**
	 * 获取properties中的值
	 * 
	 * @param propertityFile
	 *            properties的文件名
	 * @param keyInProperties
	 *            properties的key值
	 * @return String properties的值
	 **/
	public static String getPropertiesValue(String propertityFile, String keyInProperties) throws WTException
	{
		String valueInProperties = "";

		PropertyResourceBundle prBundle = (PropertyResourceBundle) PropertyResourceBundle.getBundle(propertityFile);
		try
		{
			byte[] temp = null;
			temp = keyInProperties.getBytes("GB2312");
			keyInProperties = new String(temp, "ISO-8859-1");
			temp = prBundle.getString(keyInProperties).getBytes("ISO-8859-1");
			valueInProperties = new String(temp, "GB2312");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return valueInProperties.trim();

	}

	/**
	 *根据PBO的对象类别以及所属产品库或存储库，得到其对应的电子签名配置文件
	 */
	public static String getConfigFilePath(Persistable pbo) throws IOException, WTException
	{
		String configFilePath = "";
		if (pbo instanceof WTContained)
		{
			WTContained containedObj = (WTContained) pbo;
			WTContainer container = containedObj.getContainer();
			configFilePath = getConfigFilePath(container, pbo.getClass());
		}
		else
		{
			throw new WTException("	当前对象类型没有对应的打印配置表.");
		}
		return configFilePath;
	}

	/**
	 *根据容器以及对象类型，得到其对应的流程配置文件文件
	 */
	public static String getConfigFilePath(WTContainer container, Class objClass) throws IOException, WTException
	{
		outDebugInfo( ".getConfigFilePath()");
		String configFilePath = "";
		String propertyName = "";
		String orgName = container.getOrganizationName();
		String containerName = container.getName();

		// 获取容器以及对象类的配置文件标识
		String containerLabel = (String) container2label.get(container.getClass().getName());
		String classLabel = (String) class2label.get(objClass.getName());
		if (containerLabel == null || classLabel == null)
		{
			Locale locale = SessionHelper.manager.getLocale();
			throw new WTException("	not found configurationitem for the container type(" + containerLabel + ")");
		}

		propertyName = "ext." + orgName + "." + containerLabel + "." + containerName + "." + classLabel + "." + ES_CFG;

		// 如果site.conf里没有定义，则使用缺省的ext.组织名称.default.doc.eSignatureCfg
		configFilePath = wtProperties.getProperty(propertyName, "");
		if (configFilePath == null || configFilePath.length() == 0)
		{
			propertyName = "ext." + orgName + "." + "default." + classLabel + "." + ES_CFG;
			configFilePath = wtProperties.getProperty(propertyName, "");
		}

		configFilePath = configFilePath.replace('/', File.separatorChar);
		configFilePath = configFilePath.replace('\\', File.separatorChar);
		if (configFilePath.length() == 0)
		{
			throw new WTException("	configFilePath not found config int the wtProperties file");
		}
		outDebugInfo("	ConfigFilePath=" + configFilePath);
		outDebugInfo(".getConfigFilePath()");
		return configFilePath;
	}

	/**
	 *获取Excel表格中的内容
	 */
	public static String getExcelCellContent(XSSFSheet sheet, int nRow, int nCol)
	{
		if (sheet == null || nRow < 0 || nCol < 0)
			return "";
		try
		{
			XSSFRow row = sheet.getRow(nRow);
			if (row == null)
				return "";
			XSSFCell aCell = row.getCell(nCol);
			if (aCell == null)
				return "";
			String content = aCell.getStringCellValue();
			if (content != null)
				content = content.trim();
			if (content == null)
				content = "";
			return content;
		}
		catch (Exception e)
		{
			System.out.println("	getExcelCellContent : error, nRow = '" + nRow + "' , nCol = '" + nCol + "'");
			e.printStackTrace();
		}
		return "";
	}

	public static String getObjectType(WTObject object) throws IOException, WTException
	{
		String docType = "";
		Locale locale = SessionHelper.manager.getLocale();
		docType = ClientTypedUtility.getLocalizedTypeName(object, locale);
		return docType;
	}
	public static Hashtable getConfigInforPart(WTObject pbo,String pagetype) throws IOException, WTException
	{
		Hashtable configinfor = PdfReadExcelGuidUtil.getConfigInfoForDoc(pbo, "part", "图样文件", pagetype);
		outDebugInfo(" getConfigInforPart=" + configinfor);
		return configinfor;
	}
	/**
	 * Method main 一般用于测试
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) throws Exception
	{
		System.out.println("Test");
	}

}
